<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="离职日期" >
        <el-date-picker clearable
          v-model="queryParams.quitDate"
          type="date"
          size="small"
          value-format="yyyy-MM-dd"
          placeholder="请选择离职日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请单编号">
        <el-input
          v-model="queryParams.applyNo"
          placeholder="请输入申请单编号"
          clearable
          size="small"
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button type="primary" size="small" icon="el-icon-plus"  v-hasPermi="['quit:apply:create']" @click="handleAdd">创建离职申请</el-button>
    </el-row>

    <el-table v-loading="loading" :data="deployList">
      <el-table-column label="申请单编号" prop="applyNo" align="center" width="180">
        <template slot-scope="scope">
            <el-link type="primary" @click="handleView(scope.row)">{{scope.row.applyNo}}</el-link>
        </template>
      </el-table-column>

      <el-table-column label="离职日期" align="center" prop="quitDate" :show-overflow-tooltip="true"/>
      <el-table-column label="离职原因" align="center" prop="quitRemarks" :show-overflow-tooltip="true" />
      <el-table-column label="是否完成交接" align="center" prop="isHandover" :show-overflow-tooltip="true" >
         <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isHandover==1">已交接</el-tag>
            <el-tag type="info" v-if="scope.row.isHandover==0">未交接</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否归还设备" align="center" prop="isReturnEquipment">
        <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.isReturnEquipment==1">已归还</el-tag>
            <el-tag type="info" v-if="scope.row.isReturnEquipment==0">未归还</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前审批人" align="center" prop="currApprovedBy" />
      <el-table-column label="申请单状态" align="center" prop="status" >
        <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0" type="info">草稿</el-tag>
            <el-tag v-if="scope.row.status==1" type="primary">待审批</el-tag>
            <el-tag v-if="scope.row.status==2" type="danger">审批驳回</el-tag>
            <el-tag v-if="scope.row.status==3" type="success">流程结束</el-tag>
            <el-tag v-if="scope.row.status==4" type="danger">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交人" align="center" prop="createBy" />
      <el-table-column label="提交时间" align="center" prop="createTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            {{parseTime(scope.row.modifyTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope" >
            <el-tooltip class="item" effect="dark" content="撤销申请" placement="top" v-hasPermi="['quit:apply:cancel']">
                <el-button
                    size="mini"
                    circle type="warning"
                    icon="el-icon-refresh-left"
                    v-if="scope.row.status==1"
                    @click="cancelApply(scope.row)"
                />
            </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="创建离职申请" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
        <el-form :model="quitFormData" ref="quitFormData" :rules="rules" label-width="120px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="离职日期" prop="quitDate">
                        <el-date-picker
                            :disabled="isView"
                            style="width:60%"
                            v-model="quitFormData.quitDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择开始日期时间">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否完成交接" prop="isHandover">
                        <el-radio label="1" v-model="quitFormData.isHandover">是</el-radio>
                        <el-radio label="0" v-model="quitFormData.isHandover">否</el-radio>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                    <el-form-item label="是否归还设备" prop="isReturnEquipment">
                        <el-radio label="1" v-model="quitFormData.isReturnEquipment">是</el-radio>
                        <el-radio label="0" v-model="quitFormData.isReturnEquipment">否</el-radio>
                    </el-form-item>
              </el-col>
              <el-col :span="12">
                    <el-form-item label="初审部门" prop="approvedDept">
                      <el-cascader style="width: 81%;" @change="changeDept" v-model="quitFormData.approvedDeptModel" :disabled="isView"
                        :options="deptOptions"
                        :props="props"
                        clearable></el-cascader>
                    </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="离职原因" prop="quitRemarks">
                <el-input v-model="quitFormData.quitRemarks" type="textarea"  :disabled="isView"></el-input>
            </el-form-item>
            <el-form-item label="抄送人" prop="ccUsers">
              <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
              <el-button type="info" plain size="mini" v-if="!isView" icon="el-icon-plus" @click="handleUser" >选择抄送人</el-button>
              <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearUser" v-if="ccUserList.length>0 && !isView">清空抄送人</el-button>
            </el-form-item>
            <el-form-item label="上传附件" >
              <el-upload :disabled="isView"
                class="upload-demo"
                :action="upload.url"
                :headers="headers"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
                :file-list="fileList">
                <el-button size="mini" plain v-if="!isView">点击上传</el-button>
              </el-upload>
            </el-form-item>
        </el-form>
        <div >
          <approvalHistory :processId="quitFormData.processId" v-if="quitFormData.processId && dialogVisible"></approvalHistory>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" v-if="!isView" :loading="submitLoading">提 交</el-button>
            <el-button @click="handleClose">取 消</el-button>
        </div>
    </el-dialog>

    <!-- <el-dialog title="文件预览" :visible.sync="previewDialogVisible" width="50%">
      <iframe id="iframeRef" ref="iframeRef" :src="iframeUrl" class="ifsty"></iframe>
    </el-dialog> -->
    <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
      <deptUser @getTaskUser="getCCuser" :multiple="true" v-if="dialogVisibleUser"></deptUser>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {findQuitApplyPageList,addOrUpdateQuitApply,cancelQuitApply} from "@/api/workflow/quitApply"
import { treeselectAll } from "@/api/system/dept";
import approvalHistory from '../../components/workflow/approvalHistory'
import deptUser from '../../components/userSelect/deptUser.vue'

export default {
  name: "quitApply",
  components: {
    approvalHistory,
    deptUser
  },
  data() {
    return {
      // iframeUrl:null,
      props:{multiple: true},
      // 遮罩层
      loading: true,
      submitLoading:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 参数表格数据
      deployList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramName: undefined,
        paramKey: undefined,
        paramType: undefined
      },
      dialogVisible:false,
      dialogVisibleUser:false,
      quitFormData:{

      },
      rules:{
        quitDate:[{ required: true, message: "请选择离职时间", trigger: "blur"}],
        isHandover:[{ required: true, message: "请选择是否完成交接", trigger: "blur"}],
        isReturnEquipment:[{ required: true, message: "请选择是否归还设备", trigger: "blur"}],
        quitRemarks:[{ required: true, message: "请填写离职原因", trigger: "blur"}],
      },
      leaveTypeList:[],
      isView:false,
      deptOptions:[],
      fileList:[],
      upload:{
        url: process.env.VUE_APP_BASE_API + "/test/uploadImage",
      },
      previewDialogVisible:false,
      ccUserList:[]

    };
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("leave_type").then(response => {
      this.leaveTypeList = response.data;
    });

  },
  methods: {
    handleUser(){
      this.dialogVisibleUser = true
    },
    clearUser(){
      this.ccUserList=[]
      this.leaveFormData.ccUsers=null
    },
    getCCuser(data,isClose){
      this.ccUserList = data
      if(data){
        let ccUser = []
        for(let i=0;i<data.length;i++){
          ccUser.push(data[i].userName)
        }
        this.quitFormData.ccUsers = ccUser.join(',')
      }
      this.dialogVisibleUser = isClose
    },
    preFile(fileName){
      window.open(process.env.VUE_APP_BASE_API + "/school/file/" +fileName)
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
      treeselectAll().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      findQuitApplyPageList(this.queryParams).then(response => {
          this.deployList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        paramName: undefined,
        paramKey: undefined,
        paramValue: undefined,
        paramType: "Y",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams={
        pageNum: 1,
        pageSize: 10,
        quitDate:null,
        applyNo:null
      }
      this.handleQuery();
    },
    resetForm(){
        this.quitFormData={
            quitDate:undefined,
            isHandover:undefined,
            isReturnEquipment:undefined,
            quitRemarks:undefined
        }
    },
    handleView(row){
        this.fileList = []
        this.isView = true
        this.quitFormData = row
        const deptArray = row.approvedDept.split(';')
        let approvedDeptArray = []
        for(let i=0;i<deptArray.length;i++){
          let dataIntAry = deptArray[i].split(',')
          approvedDeptArray.push(dataIntAry.map(item=>{
            return +item
          }))
        }
        this.quitFormData.approvedDeptModel = approvedDeptArray
        if(row.fileList){
          const sFile = row.fileList.split(',')
          for(let i=0;i<sFile.length;i++){
            this.fileList.push({
              url:sFile[i],
              name:row.fileResourceNames.split(',')[i]
            })

          }
        }
        if(row.ccUsers){
          this.ccUserList = row.ccUsers.split(',').map(item=>{
              return {userName:item}
          })
        }

        this.dialogVisible = true
    },
    handleClose(done){
        this.dialogVisible = false
    },
    handleAdd(){
        this.resetForm()
        this.dialogVisible = true
        this.isView = false
        this.fileList =[]
        this.ccUserList=[]
    },
    submitForm(){
        console.log(this.quitFormData)
        console.log(this.fileList)
        this.getFormFileList()
        console.log(this.quitFormData)
        this.$refs["quitFormData"].validate(valid => {
            if(valid){
                this.quitFormData.status=1
                this.submitLoading = true
                addOrUpdateQuitApply(this.quitFormData).then(resp=>{
                    this.submitLoading=false;
                    this.$message({ message: '提交成功', type: 'success' });
                    this.dialogVisible = false
                    this.getList()
                })
            }
            this.submitLoading=false;
        })
    },
    cancelApply(row){
        this.$confirm('确定要撤销请假申请吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            const applyData = {
                processInstanceId: row.processId
            }
            this.loading = true
            cancelQuitApply(applyData).then(resp=>{
                this.$message({ type: 'success', message: '撤销成功!'});
                this.getList()
            })

        })
    },
    changeDept(item){
      console.log(item)
      if(item.length>0){
        let depts = []
        for(let i=0;i<item.length;i++){
          depts.push(item[i].join(','))
        }
        this.quitFormData.approvedDept = depts.join(';')
      }

    },
    handleRemove(file, fileList) {
      //删除文件是触发
        console.log(file, fileList);
        this.fileList = fileList

    },
    handlePreview(file) {
      //点击文件是触发预览
      console.log(file);
      this.preFile(file.url)
      // window.open('https://view.officeapps.live.com/op/view.aspx?src=' + );
    },
    handleExceed(files, fileList) {
      //文件上传数量超过执行数量
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      //删除文件之前触发
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleSuccess(response, file, fileList){
      //文件上传成功时触发
      console.log("response",response,file,fileList)
      this.getFileList(fileList)
    },
    getFileList(allFileList){
      if(!allFileList) {
        return
      }
      for(let i=0;i<allFileList.length;i++){
        if(allFileList[i].response){
          this.fileList.push({
          name:allFileList[i].name,
          url:allFileList[i].response.result
        })
        }

      }
    },
    getFormFileList(){
      if(this.fileList){
        let names = []
        let urls = []
        for(let i=0;i<this.fileList.length;i++){
           names.push(this.fileList[i].name)
           urls.push(this.fileList[i].url)
        }
        this.quitFormData.fileResourceNames = names.join(',')
        this.quitFormData.fileList = urls.join(',')
      }
    }
  }
};
</script>

<style scoped>
.ifsty{
  width: 100%;
    height: 500px;
    border: 0px;
}
</style>
